package com.pphh.demo;

import com.pphh.demo.strategy.ShardStrategy;
import groovy.lang.GroovyClassLoader;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * load groovy class dynamically
 *
 * @author huangyinhuang
 * @date 9/25/2018
 */
public class DynamicGroovyStrategy {

    public static void main(String[] args) throws Exception {
        DynamicGroovyStrategy dynamicStrategy = new DynamicGroovyStrategy();
        dynamicStrategy.run(101L);
    }

    public void run(Long id) throws IOException, IllegalAccessException, InstantiationException {
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        GroovyClassLoader loader = new GroovyClassLoader(systemClassLoader);

        URL url = DynamicGroovyStrategy.class.getClassLoader().getResource("TestShardStrategy.groovy");
        File file = new File(url.getFile());
        Class groovyClass = loader.parseClass(file);

        ShardStrategy shardStrategy = (ShardStrategy) groovyClass.newInstance();
        String dbShard = shardStrategy.calculateDbShard(id);
        String tableShard = shardStrategy.calculateTableShard(id);
        System.out.println(String.format("db = %s, table = %s", dbShard, tableShard));
    }

}
